package celiasoft.itasalibtest;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import celiasoft.itasalib.query.QueryFactory;
import celiasoft.itasalib.query.ShowThumbQuery;


public class ItasaLibTestActivityItasa extends Activity {

	private static final String TAG = "itasalib.test.ItasaLibTestActivity";
	private final static String TEMP_APIKEY = "f5630249d30f459738da06afc9426e29";
	private AsyncQueryLoader _loader = new AsyncQueryLoader();
	
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
		/*
		Window window = getWindow();  
		window.addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);*/
		
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        System.setProperty("http.agent", "Italiansubs-android-lib-testapp");
        
        QueryFactory factory = QueryFactory.getInstance(this, ItasaLibTestActivityItasa.TEMP_APIKEY);    
        factory.initializeAuthcode("9bd4dc9406f24a18bf16baf598436575");
        
        final Button load = (Button) findViewById(R.id.button1);
        /*
        final MyItasaLastSubsQuery query = factory.makeMyItasaLastSubsQuery();
        
        final IQueryTaskListener listener = new IQueryTaskListener(){

			public void onComplete(QueryResult result) {
				String text = "";
		        
		        if(result.isStatusOk()){
		        	List<DataElement> news = result.getDataResult();
		        	for(DataElement el: news){
		        		MyItasaSubtitle s = (MyItasaSubtitle)el;
		        		text +=  s.getId() + ") "+ s.getName() + "\n version:" + s.getVersion() + "\n download date:" + s.getDownloadDate()+ "\n";
		        	}
		        	text +=  "\n More data? " + result.isThereMoreData();
		        }else{
		        	QueryResultError err = result.getQueryResultError();
		        	text = "ERROR CODE:" + err.getErrorCode();
		        	text += "\nERROR MSG:" + err.getErrorMessage();
		        }
		        
		        TextView tv = (TextView) findViewById(R.id.debugText);
		        tv.setMovementMethod(new ScrollingMovementMethod());
		        tv.setText(text.isEmpty()?"Unable to load data.":text);
		        
		        load.setEnabled(true);
			}

			public void onStartTask() {
				load.setEnabled(false);
				
			}};
        
        */
        /*
        final MyItasaRemoveShowQuery query = factory.makeMyItasaRemoveShowQuery(2897);        
        final IQueryTaskListener listener = new IQueryTaskListener(){

			public void onComplete(QueryResult result) {
				String text = "";
		        
		        if(result.isStatusOk()){
		        	List<DataElement> news = result.getDataResult();
		        	for(DataElement el: news){
		        		MyItasaShow s = (MyItasaShow)el;
		        		text +=  s.getName() + "\n subs:" + s.getVersionOfAvailableSubs() + "\n";
		        	}
		        	text +=  "\n More data? " + result.isThereMoreData();
		        }else{
		        	QueryResultError err = result.getQueryResultError();
		        	text = "ERROR CODE:" + err.getErrorCode();
		        	text += "\nERROR MSG:" + err.getErrorMessage();
		        }
		        
		        TextView tv = (TextView) findViewById(R.id.debugText);
		        tv.setMovementMethod(new ScrollingMovementMethod());
		        tv.setText(text.isEmpty()?"Unable to load data.":text);
		        
		        load.setEnabled(true);
			}

			public void onStartTask() {
				load.setEnabled(false);
				
			}};
        
        */
        
        /**************************************/
        
        final ShowThumbQuery query = factory.makeThumbShowQuery(2897);        
        
		
        load.setOnClickListener(new OnClickListener(){

			public void onClick(View arg0) {
				_loader.load(new Runnable(){

					public void run() {
						Bitmap image =  query.getImageResult();
						
						if(image == null){
							Log.d(TAG, "fail");
						}else{
							Log.d(TAG, "succes");
						}
						
						/*
							//fetch(new URL("https://api.italiansubs.net/api/rest/shows/2897/folderThumb?apikey=f5630249d30f459738da06afc9426e29"));
							//fetch(new URL("https://api.italiansubs.net/api/rest/shows/2897?apikey=f5630249d30f459738da06afc9426e29"));
							
							//DownloadFileFromUrl.DownloadFromUrl("https://api.italiansubs.net/api/rest/shows/2897/folderThumb?apikey=f5630249d30f459738da06afc9426e29", "test.png");
							//DownloadBitmapFromUrl.DownloadFromUrl("https://api.italiansubs.net/api/rest/shows/2897/folderThumb?apikey=f5630249d30f459738da06afc9426e29", "test.png");
							DownloadFileFromUrl.DownloadFromUrl("https://api.italiansubs.net/api/rest/shows/2897?apikey=f5630249d30f459738da06afc9426e29", "test.xml");

						*/
						
					}
					
				});
				
			}
        	
        });
        
        
        
        
        
	}
	
	
	
	private static final int COPY_BUFFER_SIZE = 4096;
	
	public static byte[] fetch(URL remoteUrl) throws IOException {

			//Fetch through HTTP
			HttpsURLConnection urlConnection = (HttpsURLConnection)remoteUrl.openConnection();
			urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            //urlConnection.connect();
			
			InputStream stream = urlConnection.getInputStream();
			Log.d(TAG, "remoteUrl: " + remoteUrl);
			//Read
			ByteArrayOutputStream buffer = new ByteArrayOutputStream();
			int nRead = 0;
			byte[] copyBuffer = new byte[COPY_BUFFER_SIZE];
			
			Log.d(TAG,"FILE OUTPUT #");
			int  totRead = 0;
			while((nRead = stream.read(copyBuffer)) != -1){
				
				//System.out.write(copyBuffer, 0, nRead);
				//System.out.println("writeline");
				buffer.write(copyBuffer, 0, nRead);
				totRead += nRead;
			}
			
			Log.d(TAG,"# FILE OUTPUT tot read=" + totRead);
			//Finalize
			buffer.flush();
			stream.close();
			
			return buffer.toByteArray();
			
	}
	
	
}